﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
using System.Windows.Forms;
using Microsoft.Win32;


namespace jSLCore.VSPackageRegistering
{
    [RunInstaller(true)]
    public partial class AssenblyInstaller : System.Configuration.Install.Installer
    {
        private const string JslcoreName = "jSLCore";

        public AssenblyInstaller()
        {
            InitializeComponent();
        }

        
        public override void Uninstall(IDictionary savedState)
        {
            Uninstall();

            base.Uninstall(savedState);
        }

        public static void Uninstall()
        {
            var softwareFolder =
                Registry.LocalMachine.OpenSubKey("SOFTWARE");

            var exFolders = softwareFolder.FindSubKey("AssemblyFoldersEx");
            foreach (var exFolder in exFolders)
            {
                var name = exFolder.Name.ToUpper();
                if (IsNetFrameworkFolder(name) || IsSilverLightFolder(name))
                {
                    var coreKey = exFolder.OpenSubKey(JslcoreName, true);
                    if (coreKey != null)
                    {
                        exFolder.DeleteSubKeyTree(JslcoreName);
                    }
                }
            }
        }

        public override void Install(IDictionary stateSaver)
        {
            try
            {
                var path = Context.Parameters["targetDir"].TrimEnd('\\') + '\\';

                Install(path);

                InstallVSIX(path);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw new Exception();
            }

            /*{
                

                var subs = softwareFolder.GetSubKeyNames();

                foreach (var sub in subs)
                {
                    if (sub.Contains("v4.0"))
                    {
                        var assemblyFolder = softwareFolder.OpenSubKey(sub).OpenSubKey("AssemblyFoldersEx",
                                                                                     RegistryKeyPermissionCheck.
                                                                                         ReadWriteSubTree,
                                                                                     RegistryRights.FullControl);

                        var registryKey = assemblyFolder.CreateSubKey("jSLCore");

                        registryKey.SetValue(string.Empty, path, RegistryValueKind.String);


                        break;
                    }
                }
            }

            {
                var msFolder = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Microsoft");

                if (System.Environment.Is64BitOperatingSystem)
                {
                    msFolder = msFolder.OpenSubKey("Wow6432Node");
                }

                var targetFolrder =
                    msFolder.OpenSubKey("Microsoft SDKs").OpenSubKey("Silverlight").OpenSubKey(
                        "v4.0").OpenSubKey("AssemblyFoldersEx",
                                                                                     RegistryKeyPermissionCheck.
                                                                                         ReadWriteSubTree,
                                                                                     RegistryRights.FullControl);
                var registryKey = targetFolrder.CreateSubKey("jSLCore");
                registryKey.SetValue(string.Empty, path, RegistryValueKind.String);
            }*/


           // System.IO.File.Copy(path + "jSLApp.zip", System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Visual Studio 2010\" + @"Templates\ProjectTemplates\" + "jSLApp.zip",true);

            base.Install(stateSaver);

        }

        private void InstallVSIX(string path)
        {
            var VSIXPath = Path.Combine(path, "jSLCoreInstaller.vsix");
            Process.Start(VSIXPath).WaitForExit();
        }

        public static void Install(string path)
        {
            var softwareFolder =
                Registry.LocalMachine.OpenSubKey("SOFTWARE");

            if(softwareFolder==null)throw new InvalidOperationException(@"Не найдено: HKEY_LOCAL_MACHINE\SOFTWARE");

            var exFolders = softwareFolder.FindSubKey("AssemblyFoldersEx");
            foreach (var exFolder in exFolders)
            {
                var name = exFolder.Name.ToUpper();
                if (IsNetFrameworkFolder(name))
                {
                    SetValue(path+".NET\\", exFolder);
                }
                else
                if (IsSilverLightFolder(name))
                {
                    SetValue(path+"SilverLight\\", exFolder);
                }
            }
        }

        private static void SetValue(string path, RegistryKey exFolder)
        {
            var coreKey = exFolder.CreateSubKey(JslcoreName, RegistryKeyPermissionCheck.ReadWriteSubTree);
            coreKey.SetValue(string.Empty, path, RegistryValueKind.String);
            coreKey.Flush();
            coreKey.Dispose();
        }

        private static bool IsSilverLightFolder(string name)
        {
            return ( name.Contains("v5.0".ToUpper()) && name.Contains("Silverlight".ToUpper()) );
        }

        private static bool IsNetFrameworkFolder(string name)
        {
            return ( name.Contains("v4.0".ToUpper()) && name.Contains(".NETFramework".ToUpper()) && name.Contains("microsoft".ToUpper()) );
        }
    }
}
